<#import "/spring.ftl" as spring />
<#assign ctx= request.contextPath/>
<!doctype html>
<!--[if lt IE 7]>
<html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>
<html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>
<html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<head>
    <#--    <base href="<@spring.url basePath/>">-->
    <#--    <meta charset="utf-8">-->
    <#--    <meta http-equiv="X-UA-Compatible" content="IE=edge">-->
    <#--    <title>Eureka</title>-->
    <#--    <meta name="description" content="">-->
    <#--    <meta name="viewport" content="width=device-width">-->

    <#--    <link rel="stylesheet" href="${ctx}/eureka/css/wro.css">-->
    <title>DownUp Service!</title>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="${ctx}/eureka/css/wro.css">
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <script type="text/javascript" src="eureka/js/wro.js"></script>
    <script src="https://cdn.bootcss.com/layer/3.1.0/layer.js"></script>
    <#--  layui 组件地址  -->
    <#--    <script src="${ctx}/eureka/layui.js"></script>-->
    <script src="https://www.layuicdn.com/layui-v2.5.5/layui.js"></script>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.5/css/layui.css" media="all">
    <#--    <link rel="stylesheet" href="${ctx}/eureka/js/css/layui.css" media="all">-->

    <#--    #cssText{-->
    <#--    width: 50px; /* 容器宽度 */-->
    <#--    white-space: nowrap; /* 文本不换行 */-->
    <#--    overflow: hidden; /* 内容会被修剪，并且超过设置宽度的内容是不可见的 */-->
    <#--    text-overflow: ellipsis;/*显示省略符号来代表被修剪的文本*/-->
    <#--    }-->
    <#--    //超出2行文本显示省略号-->
    <#--    //width: 280rpx;   //自己定宽度-->
    <#--    //white-space: nowrap;  //需要注释掉-->
    <#--    overflow: hidden; //超出隐藏-->
    <#--    text-overflow: ellipsis;  //文本超出，用ellipsis省略号-->
    <#--    //显示多行-->
    <#--    display: -webkit-box;/* 弹性盒模型 */-->
    <#--    -webkit-box-orient: vertical;/* 元素垂直居中*/-->
    <#--    -webkit-line-clamp: 2;/*  文字显示的行数*/-->

    <style type="text/css">
        p {
            text-align: left; /*文本左对齐*/
            font-size: 18px; /*字体大小 18 像素*/
            line-height: 25px; /*行高 25 像素*/
            text-indent: 2em; /*首行缩进2个文字大小空间*/
            width: 500px; /*段落宽度 500 像素*/
            margin: 0 auto; /*浏览器下居中*/
            margin-bottom: 20px; /*段落下边距 20 像素*/
        }

        cssText {
            width: 50px; /* 容器宽度 */
            white-space: nowrap; /* 文本不换行 */
            overflow: hidden; /* 内容会被修剪，并且超过设置宽度的内容是不可见的 */
            text-overflow: ellipsis; /*显示省略符号来代表被修剪的文本*/
        }

        /*.contain {*/
        /*    font-family: ' Microsoft YaHei ';*/
        /*    margin: 15px auto;*/
        /*    width: 900px;*/
        /*}*/

        table {
            border: 1px solid #e3e6e8;
            border-collapse: collapse;
            display: table;
            table-layout: fixed;
            text-align: left;
            width: 10%;
        }

        td {
            border: 1px solid #e3e6e8;
            height: 38px;
            line-height: 3px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .bold {
            font-weight: bold
        }

        th {
            background-color: #189AD6;
            color: #fff;
        }

        /*.layui-layer {*/
        /*    word-break: break-all;*/
        /*    word-wrap: break-word;*/
        /*}*/

    </style>
</head>

<body id="one">
<#include "header.ftl">
<div class="container-fluid xd-container">
    <h1>Task History For This Service</h1>

    <table id='instances' class="table table-striped table-hover">
        <thead>
        <tr>
            <th width="80px" fixed="true">ServiceName</th>
            <th width="80px" fixed="true">TASKTYPE</th>
            <th width="120px" fixed="true">StartTime</th>
            <th width="120px" fixed="true">EndTime</th>
            <th width="50px" fixed="true">SpendTime</th>
            <th width="50px" fixed="true">IsSuccess</th>
            <th width="100px" fixed="true">JarInfo</th>
            <th width="100px" fixed="true">ServerHostInfo</th>
            <th width="500px" fixed="true">TaskInfos</th>
        </tr>
        </thead>
        <tbody>
        <#if serviceTaskInfoMap ? has_content>
            <#list serviceTaskInfoMap as taskWrapper>
                <tr>
                    <td><b><#if taskWrapper.serviceName??>${taskWrapper.serviceName}</#if></b></td>
                    <td><b><#if taskWrapper.taskType??>${taskWrapper.taskType}</#if></b></td>
                    <td><b><#if taskWrapper.startTime??>${taskWrapper.startTime}</#if></b></td>
                    <td><b><#if taskWrapper.endTime??>${taskWrapper.endTime}</#if></b></td>
                    <td><b><#if taskWrapper.totalSpend??>${taskWrapper.totalSpend}</#if></b></td>
                    <td>
                        <#if taskWrapper.endTime?? && taskWrapper.endTime != "" && taskWrapper.totalSpend ?? && taskWrapper.totalSpend != "定时替换已取消">
                            <b><#if taskWrapper.success?? && taskWrapper.success>
                                    <font color=green>成功</font>
                                <#else>
                                    <font color=red>失败</font>
                                </#if>
                            </b>
                        <#else>
                            <#if taskWrapper.taskType?? && taskWrapper.taskType =="定时服务替换" && taskWrapper.totalSpend ?? && taskWrapper.totalSpend != "定时替换已取消">
                                <font color=green>定时任务还未开始</font>
                            </#if>
                        </#if>
                    </td>
                    <td><b><#if taskWrapper.jarInfo??>${taskWrapper.jarInfo}</#if></b></td>
                    <td><b><#if taskWrapper.serverHostInfo??>${taskWrapper.serverHostInfo}</#if></b></td>
                    <td>
                        <#if taskWrapper.taskInfos ? has_content>
                        <#--                            <p id="openBtn${taskWrapper?index}" onclick="openfunction(${taskWrapper?index})">展开全部</p>-->
                        <#--                            <b id="taskInformation${taskWrapper?index}" class="">-->
                            <#list taskWrapper.taskInfos as taskInfo>
                                <#if taskInfo?index gt 1>
                                    <div hidden>
                                        <font class="bold">任务${taskInfo?index}</font>
                                        <b><#if taskInfo.startTime??>开始: ${taskInfo.startTime}</#if></b>
                                        <b><#if taskInfo.endTime??>结束: ${taskInfo.endTime}</#if></b>
                                        <b><#if taskInfo.spendTime??>耗时: ${taskInfo.spendTime}s</#if></b>
                                        <b><#if taskInfo.taskDes??>描述: ${taskInfo.taskDes}</#if></b>
                                        <p></p>
                                    </div>
                                <#else>
                                    <div>
                                        <font class="bold">任务${taskInfo?index}</font>
                                        <b><#if taskInfo.startTime??>开始: ${taskInfo.startTime}</#if></b>
                                        <b><#if taskInfo.endTime??>结束: ${taskInfo.endTime}</#if></b>
                                        <b><#if taskInfo.spendTime??>耗时: ${taskInfo.spendTime}s</#if></b>
                                        <b><#if taskInfo.taskDes??>描述: ${taskInfo.taskDes}</#if></b>
                                    </div>
                                </#if>
                            </#list>
                        <#--                            </b>-->
                        </#if>
                    </td>

                    <#--                    <td>-->
                    <#--                        <#list app.zoneCounts as zoneCount>-->
                    <#--                            <b>${zoneCount.key}</b> (${zoneCount.value})<#if zoneCount_has_next>,</#if>-->
                    <#--                        </#list>-->
                    <#--                    </td>-->
                    <#--                    <td>-->
                    <#--                        <#list app.instanceInfos as instanceInfo>-->
                    <#--                            <#if instanceInfo.isNotUp>-->
                    <#--                                <font color=red size=+1><b>-->
                    <#--                            </#if>-->
                    <#--                            <b>${instanceInfo.status}</b> (${instanceInfo.instances?size}) --->
                    <#--                            <#if instanceInfo.isNotUp>-->
                    <#--                                </b></font>-->
                    <#--                            </#if>-->
                    <#--                            <#list instanceInfo.instances as instance>-->
                    <#--                                <#if instance.isHref>-->
                    <#--                                    <a href="${instance.url}" target="_blank">${instance.id}</a>-->
                    <#--                                <#else>-->
                    <#--                                    ${instance.id}-->
                    <#--                                </#if><#if instance_has_next>,</#if>-->
                    <#--                            </#list>-->
                    <#--                        </#list>-->
                    <#--                    </td>-->
                </tr>
            </#list>
        <#else>
            <tr>
                <td colspan="9">没有任务历史记录</td>
            </tr>
        </#if>
        </tbody>
    </table>

    <h1>Jar List On DownUp Server For This Service</h1>
    <div>
        <div id="hideBeforeSelectFile" hidden="hidden"></div>
        <input type="file" class="filebutton" id="fileNo"
               onchange="fileSelected()"/>
        <#--                        <input type="file" class="filebutton${dto?index}" id="fileNo${dto?index}" />-->
        <#--版本信息-->
        <div id="hideBeforeNewVersion" hidden="hidden"><font color="red">本次上传Jar的版本号（必填，不填默认为文件修改日期）</font>
            <input type="text" id="newVersion" hidden="hidden"/>
        </div>
        <button id="confirmUpload" hidden="hidden" onclick="confirmUpload()">
            确定上传
        </button>
        <div id="confirmUploadResult"></div>
    </div>

    <table id='instances' class="table table-striped table-hover">
        <tbody>
        <b id="serviceNameForRollback" hidden="hidden">${serviceName}</b>
        <#if jarInfo?has_content>
            <#list jarInfo as info>
                <tr>
                    <#--                    <#if info?length gt 5>-->
                    <#--                    ${info?substring(0 ,4)}-->
                    <#--                    -->
                    <#--                    <#else>${info}</#if>-->
                    <#--&lt;#&ndash;                    <#if ${info?substring(0,4) == "没有文件夹"}>&ndash;&gt;-->
                    <#--&lt;#&ndash;                    <td><b>${info}</b></td>&ndash;&gt;-->
                    <#--                <#else>-->
                    <td>
                        <b id="deleteJarIndex${info?index}" hidden="hidden">${info}</b>
                        <b>${info}
                            <div id="deleteJar">
                                <button id="deleteJar${info?index}" onclick="deleteJar(${info?index})">
                                    删除jar
                                </button>
                                <div id="deleteJarResult${info?index}"></div>
                            </div>

                            <div id="rollback">
                                <button id="rollback${info?index}" onclick="rollbackService('${info}',${info?index})">
                                    回滚
                                </button>
                                <div id="rollbackResult${info?index}"></div>
                            </div>

                            <div></div>
                            <b></b>
                            <p></p>
                            <#--    <input type="text" id="demoTest">-->
                            <div id="scheduleTask">
                                <#--                                                                <input type="text" class="demo-input" placeholder="请选择日期" id="scheduleTaskTime${info?index}">-->
                                <div id="scheduleTaskTime${info?index}">
                                    <input type="text" class="demo-input" placeholder="请选择日期" id="scheduleTaskTime">
                                    <button id="scheduleTask${info?index}"
                                            onclick="scheduleTask('${info}',${info?index})">
                                        定时任务
                                    </button>
                                </div>
                                <div id="scheduleTaskResult${info?index}"></div>
                            </div>
                        </b>
                    </td>

                </tr>
            </#list>
        <#else>
            <tr>
                <td colspan="2">没有Jar包信息</td>
            </tr>
        </#if>
        </tbody>
    </table>


</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('table.stripeable tr:odd').addClass('odd');
        $('table.stripeable tr:even').addClass('even');
    });
    // 表格文本隐藏展示
    $(function () {
        $("td").on("mouseenter", function () {
            //js主要利用offsetWidth和scrollWidth判断是否溢出。
            //在这里scrollWidth是包含内容的完全高度，offsetWidth是当前表格单元格的宽度。
            if (this.offsetWidth < this.scrollWidth) {
                var that = this;
                var text = $(this).text();
                window.layer.tips(text, that, {
                    tips: 1,
                    time: 10000,
                    area: ['800px', 'auto']
                });
            }
        });
    })

    layui.use('laydate', function () {
        var laydate = layui.laydate;
        $(".demo-input").each(function () {
            //执行一个laydate实例
            laydate.render({
                elem: this, //指定元素
                type: 'datetime',
                trigger: 'click'
            });
        })
    });

    // 文件选择
    function fileSelected() {
        console.log("调用 了 fileSelected");
        let fileNo = document.querySelector('#fileNo');
        console.log("files " + fileNo.files);
        console.log("files length" + fileNo.files.length);
        console.log("files [0]" + fileNo.files[0]);

        var file = fileNo.files[0];
        console.log("file name :" + file.name);
        var info = document.getElementById('hideBeforeSelectFile');
        console.log("file:" + file);
        var size = file.size / 1024 / 1024;

        info.innerHTML = '文件:' + file.name + '<br>' + '大小:' + size.toFixed(2) + 'M' + '<br>' + '修改:' + file.lastModifiedDate;
        info.removeAttribute("hidden");
        $('#confirmUpload').removeAttr("hidden");
        var version = $('#newVersion');
        version.removeAttr("hidden");
        $('#hideBeforeNewVersion').removeAttr("hidden");
    }

    // 开始上传, 参数为 File 对象
    function confirmUpload() {
        var formData = new FormData();
        //设置不能再次点击
        $("#confirmUpload").attr("disabled", true);
        let fileNo = document.querySelector('#fileNo');
        console.log("confirmUpload file " + fileNo.files[0]);
        var file = fileNo.files[0];
        formData.append('file', file); // 'file' 为HTTP Post里的字段名, file 对浏览器里的File对象
        var serviceName = document.getElementById('serviceNameForRollback').innerText;
        formData.append('serviceName', serviceName);

        // 处理 版本信息，如果没有则为日期时分秒，如果有则按照用户填入的
        var version = $("#newVersion");
        var date = file.lastModifiedDate;
        if (version.val() === null || version.val() === '' || typeof version.val() === 'undefined') {
            var dateString = date.toISOString().substr(0, 10).replace(/-/g, '') + date.toTimeString().substr(0, 8).replace(/:/g, '');
            version.val(dateString);
            console.log("version.value 无值：" + version.val());
        } else {
            let versionValue = version.val();
            console.log("index ....versionValue " + versionValue);
            if (versionValue.indexOf("-") >= 0) {
                console.log("index 到这里");
                alert("版本中不能包含 - ");
                throw "版本中不能包含 - ";
            }
            console.log("version.value 有值：" + version.val());
        }
        console.log("va" + version.val());
        formData.append('jarVersionInfo', version.val());
        formData.append('originalFileName', file.name);

        $.ajax({
            url: "${ctx}/uploadJar/uploadJarToLocal",
            type: 'POST',
            data: formData,  // 直接丢对象
            // ajax传文件 一定要指定两个关键性的参数
            contentType: false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            success: function (data) {
                console.log("文件上传到本地收到的data" + data);
                $("#confirmUpload").attr("hidden", "hidden");
                text = document.getElementById('confirmUploadResult').innerText;
                text += '\n' + data;
                document.getElementById('confirmUploadResult').innerText = text;
            }
        })
    }

    // 定时替换
    function scheduleTask(localFilePath, index) {
        console.log("scheduleTask - localFilePath:" + localFilePath);
        console.log("scheduleTask - index:" + index);
        var serviceName = document.getElementById('serviceNameForRollback').innerText;
        console.log("serviceName:" + serviceName);
        $("#scheduleTask" + index).attr("disabled", true);
        // var scheduleTime = document.getElementById('scheduleTaskTime' + index).innerText;
        var scheduleTime = $('#scheduleTaskTime' + index).children().val();
        console.log("scheduleTime:" + scheduleTime);
        var serviceMapVo = {
            "serviceName": serviceName,
            "localFilePath": localFilePath,
            "scheduleTime": scheduleTime
        }

        $.ajax({
            url: "${ctx}/schedule/scheduleTask",
            type: 'POST',
            contentType: "application/json", //必须这样写
            dataType: "json",
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            data: JSON.stringify(serviceMapVo),
            success: function (data) {
                console.log("定时重启接口的返回：" + data);
                $("#scheduleTask" + index).attr("hidden", "hidden");
                text = document.getElementById('scheduleTaskResult' + index).innerText;
                text += '\n' + data;
                document.getElementById('scheduleTaskResult' + index).innerText = text;
            }
        })
    }

    // 删除jar
    function deleteJar(index) {
        console.log("index:" + index);
        var localFilePath = document.getElementById('deleteJarIndex' + index).innerText;
        console.log("localFilePath:" + localFilePath);
        $("#deleteJar" + index).attr("disabled", true);
        var serviceMapVo = {
            "localFilePath": localFilePath
        }
        $.ajax({
            url: "${ctx}/localService/deleteJarByLocalPath",
            type: 'POST',
            contentType: "application/json", //必须这样写
            dataType: "json",
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            data: JSON.stringify(serviceMapVo),
            success: function (data) {
                console.log("删除jar接口的返回：" + data);
                $("#deleteJar" + index).attr("hidden", "hidden");
                text = document.getElementById('deleteJarResult' + index).innerText;
                text += '\n' + data;
                document.getElementById('deleteJarResult' + index).innerText = text;
            }
        })
    }

    // 回滚服务
    function rollbackService(localFilePath, index) {
        console.log("localFilePath:" + localFilePath);
        console.log("index:" + index);
        var serviceName = document.getElementById('serviceNameForRollback').innerText;
        console.log("serviceName:" + serviceName);
        $("#rollback" + index).attr("disabled", true);

        var serviceMapVo = {
            "serviceName": serviceName,
            "localFilePath": localFilePath
        }
        console.log("serviceMapVo: " + serviceMapVo);

        $.ajax({
            url: "${ctx}/rollback/rollback",
            type: 'POST',
            contentType: "application/json", //必须这样写
            dataType: "json",
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            data: JSON.stringify(serviceMapVo),
            success: function (data) {
                console.log("收到 回滚的 taskId" + data);
                var source = new EventSource('${ctx}/subscribe?taskId=' + data);
                source.onmessage = function (event) {
                    console.log("onmessage" + event.data);
                    text = document.getElementById('rollbackResult' + index).innerText;
                    // if (text === "bye") {
                    //     document.getElementById('onerror'+index).remove();
                    // } else {
                    text += '\n' + event.data;
                    document.getElementById('rollbackResult' + index).innerText = text;
                    // }
                };
                source.onerror = function (event) {
                    // document.getElementById('onerror').remove();
                    console.log("source.onerror CLOSED" + event);
                    source.close();
                }
            }
        })
    }
</script>
</body>
</html>
